<template>
  <div class="main">
    <mine-title>特征工程</mine-title>
    <div class="content">
      <div class="block-header">
        <div class="block-header-left">
          <mine-button @click="addFeCanvas()" type="primary"
            ><i class="iconfont icon-add-line"></i>新建工程
          </mine-button>
          <mine-button
            @click="deleteFeCanvas"
            secondary
            :disabled="!multipleSelection.length"
            ><i class="iconfont icon-delete-line"></i>删除
          </mine-button>
          <mine-button type="primary" secondary @click="loadData()"
            ><i class="iconfont icon-reset-line"></i>刷新
          </mine-button>
        </div>
        <div class="block-header-right"></div>
      </div>
      <el-table
        class="table"
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        ref="multipleTable"
      >
        <el-table-column type="selection" width="45"></el-table-column>
        <el-table-column label="序号" show-overflow-tooltip width="120">
          <template slot-scope="scope">
            <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }} </span>
          </template>
        </el-table-column>
        <el-table-column label="工程名称" prop="name" show-overflow-tooltip>
          <template slot="header">
            <span>工程名称</span>
            <mine-table-search
              @searchSubmit="searchSubmit"
              name="name"
            ></mine-table-search>
          </template>
        </el-table-column>
        <el-table-column label="所属项目" prop="itemname" show-overflow-tooltip>
          <template slot="header">
            <span>所属项目</span>
            <mine-table-search
              @searchSubmit="searchSubmit"
              name="itemname"
            ></mine-table-search>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240">
          <template slot-scope="scope">
            <mine-button
              type="text"
              @click="detail(scope.row)"
              class="button-gap"
              >详细信息</mine-button
            >
            <mine-button
              type="text"
              class="button-gap"
              @click="check(scope.row)"
              >工程详情</mine-button
            >
            <!-- <mine-button type="text" @click="openFlowChart(scope.row)"
              >画布</mine-button
            > -->
          </template>
        </el-table-column>
      </el-table>
      <mine-pagination
        @numberChange="numberChange"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
      >
      </mine-pagination>
    </div>
  </div>
</template>

<script>
import qs from "qs";
import { QWebChannel } from "@/modules/index/utils/qwebchannel.js";

export default {
  name: "FeatureEngineering",
  data() {
    return {
      listQuery: {},
      // table参数
      tableData: [],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      multipleSelection: [],
      loading: false,
      tableHeight: window.innerHeight - 330,
    };
  },
  methods: {
    openFlowChart(val) {
      this.$router.push({
        path: "/flowChart",
        query: {
          id: val.id,
        },
      });
    },
    searchSubmit(value) {
      if (value.key === "name") {
        this.listQuery.name = value.value;
      }
      if (value.key === "itemname") {
        this.listQuery.itemname = value.value;
      }
      this.loadData(true);
    },
    async loadData(flag) {
      if (flag) {
        this.currentPage = 1;
      }
      const params = {
        ...this.listQuery,
        page: this.currentPage,
        pageSize: this.pageSize,
      };
      this.loading = true;
      try {
        let res = {};
        let _self = this;
        if (_self.$qwebUtil.isQtClient) {
          const uuid = _self.$qwebUtil.generateRandomUUID();
          let sendObject;
          /* eslint-disable-next-line */
          const channel = new QWebChannel(
            window.qt.webChannelTransport,
            async function (channel) {
              // console.log(channel, 'inner')
              sendObject = channel.objects.sendObject;
              const receivedJSON = {
                RequestUrl: "/feCanvas/pageList",
                RequestMethod: "get",
                ContentType: "application/json;charset=UTF-8",
                RequestBody: qs.stringify(params, { indices: false }),
                isStringParam: true,
                requestId: uuid,
              };
              await send();
              await _self.$qwebUtil.receive(sendObject, receivedJSON);
            }
          );
          /* eslint-disable-next-line */
          async function send() {
            sendObject.sendMessage.connect(function (data) {
              if (!data) {
                console.error("[Qt]", "No data received.");
              }
              // console.error('test data', data)
              // 处理内容
              res = JSON.parse(data);
              const result = res.response || {};
              // TODO： 定制后台数据处理
              if (result.success && res.webInfo.requestId == uuid) {
                // console.log(res);
                const data = result.data;
                _self.tableData =
                  data.list && data.list.length ? data.list : [];
                _self.total = data.rowCount || 0;
              } else {
                _self.tableData = [];
                _self.total = 0;
              }
              _self.loading = false;
            });
          }
        } else if (this.$webview2.isWPF) {
          const uuid = this.$webview2.generateRandomUUID();
          await this.$webview2.sendWebView2(
            "/feCanvas/pageList",
            "get",
            "application/json;charset=UTF-8",
            qs.stringify(params, { indices: false }),
            true,
            uuid
          );
          await window.chrome.webview.addEventListener(
            "message",
            (e) => {
              res = e.data;
              const result = res.response || {};

              // TODO： 定制后台数据处理
              if (result.success && res.webInfo.requestId == uuid) {
                // console.log(res);
                const data = result.data;
                this.tableData = data.list && data.list.length ? data.list : [];
                this.total = data.rowCount || 0;
              } else {
                this.tableData = [];
                this.total = 0;
              }
              this.loading = false;
            },
            { once: true }
          );
        } else {
          res = await this.$store.dispatch(
            "feCanvasPageList",
            qs.stringify(params, { indices: false })
          );
          const result = res.data || {};
          // TODO： 定制后台数据处理
          // console.log("result", result);
          if (result.success) {
            const data = result.data;
            this.tableData = data.list && data.list.length ? data.list : [];
            this.total = data.rowCount || 0;
          } else {
            this.tableData = [];
            this.total = 0;
          }
          this.loading = false;
        }
      } catch (e) {
        console.error(e);
      }
      this.loading = false;
    },
    addFeCanvas() {
      this.$router.push({
        path: "/addFeCanvas",
      });
    },
    async deleteFeCanvas() {
      this.$mineConfirm("确认要删除这个模型", "删除提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const ids = this.multipleSelection.map((item) => item.id);
          this.loading = true;
          try {
            let res = {};
            let _self = this;
            if (_self.$qwebUtil.isQtClient) {
              const uuid = _self.$qwebUtil.generateRandomUUID();
              let sendObject;
              /* eslint-disable-next-line */
              const channel = new QWebChannel(
                window.qt.webChannelTransport,
                async function (channel) {
                  sendObject = channel.objects.sendObject;
                  // receivedJSON 修改此处发送请求参数
                  const receivedJSON = {
                    RequestUrl: `/feCanvas/deleteByIds${_self.$qwebUtil.convertIdsToQueryString(
                      ids
                    )}`,
                    RequestMethod: "post",
                    ContentType: "application/json;charset=UTF-8",
                    RequestBody: {},
                    isStringParam: false,
                    requestId: uuid,
                  };
                  await send();
                  await _self.$qwebUtil.receive(sendObject, receivedJSON);
                  // console.error('received','/feCanvas/pageList')
                }
              );
              /* eslint-disable-next-line */
              async function send() {
                sendObject.sendMessage.connect(function (data) {
                  if (!data) {
                    console.error("[Qt]", "No data received.");
                  }
                  res = JSON.parse(data);
                  const result = res.response || {};
                  if (result.success && res.webInfo.requestId == uuid) {
                    _self.$message.success("删除成功");
                    _self.loadData(true);
                  } else {
                    _self.$message.error(result.msg || "删除失败");
                  }
                });
              }
            } else if (this.$webview2.isWPF) {
              const uuid = this.$webview2.generateRandomUUID();
              await this.$webview2.sendWebView2(
                `/feCanvas/deleteByIds${this.$webview2.convertIdsToQueryString(
                  ids
                )}`,
                "post",
                "application/json;charset=UTF-8",
                {},
                false,
                uuid
              );
              await window.chrome.webview.addEventListener(
                "message",
                (e) => {
                  res = e.data;
                  const result = res.response || {};
                  if (result.success && res.webInfo.requestId == uuid) {
                    this.$message.success("删除成功");
                    this.loadData(true);
                  } else {
                    this.$message.error(result.msg || "删除失败");
                  }
                },
                {
                  once: true,
                }
              );
            } else {
              res = await this.$store.dispatch("feCanvasBatchDelete", {
                ids: ids,
              });
              // console.log(res);
              const result = res.data || {};
              if (result.success) {
                this.$message.success("删除成功");
                this.loadData(true);
              } else {
                this.$message.error(result.msg || "删除失败");
              }
            }
          } catch (e) {
            console.error(e);
          }
          this.loading = false;
        })
        .catch(() => {});
    },
    // 查看详情
    detail(val) {
      this.$router.push({
        path: "/feCanvasDetail",
        query: {
          id: val.id,
        },
      });
    },
    check(val) {
      this.$router.push({
        path: "/algoFlow",
        query: {
          id: val.id,
        },
      });
    },
    handleSelectionChange(selection) {
      this.multipleSelection = selection;
      // console.log(this.multipleSelection);
    },
    numberChange(val) {
      // console.log(val);
      switch (val.flag) {
        case "pageSize":
          this.pageSize = val.pageSize;
          this.loadData(true);
          break;
        case "currentPage":
          this.currentPage = val.currentPage;
          this.loadData(false);
          break;
        default:
          break;
      }
    },
  },
  mounted() {
    this.loadData();
  },
};
</script>

<style lang="less" scoped>
/deep/ .el-header {
  background-color: #b3c0d1;
  color: #333;
  line-height: 60px;
}

/deep/ .el-aside {
  color: #333;
}

/deep/ .el-menu {
  color: #333;
}
/deep/ .button-gap {
  margin-right: 10px;
}
</style>
